package com.cxs.componentcode.provider;

import com.cxs.componentcode.ResourceTable;
import ohos.agp.components.*;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.Optional;

public class NewTypeProvider extends BaseItemProvider {
    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MainAbility");
    private String[] newsTypeList;
    private Context context;

    public NewTypeProvider(String[] newsTypeList, Context context) {
        this.newsTypeList = newsTypeList;
        this.context = context;
    }

    @Override
    public int getCount() {
        return newsTypeList == null ? 0 : newsTypeList.length;
    }

    @Override
    public Object getItem(int i) {
        // 通过索引返回newsTypeList元素，如果值是null，则抛出异常
        return Optional.of(newsTypeList[i]);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        HiLog.info(LABEL, "getComponent");
        ViewHolder viewHolder = null;
        Component cpt = component;

        if (cpt == null) {
            HiLog.info(LABEL, "getComponent cpt == null");
            // 生成要重用的组件的对象
            cpt = LayoutScatter.getInstance(context)
                    .parse(ResourceTable.Layout_item_news_type_layout, null, false);
            viewHolder = new ViewHolder();
            // 获取生成的组件里的子组件
            Component componentText = cpt.findComponentById(ResourceTable.Id_news_type_text);
            if (componentText instanceof Text) {
                // 如果 componentText是 Text 的实例
                viewHolder.titleText = (Text)componentText;
            }
            // 将 cpt 的 tag 设为 viewHolder
            cpt.setTag(viewHolder);
        } else {
            if (cpt.getTag() instanceof ViewHolder) {
                // 如果 convertComponent 的 tag 已被设为 ViewHolder 的实例
                viewHolder = (ViewHolder) cpt.getTag();
            }
        }

        if (viewHolder!=null) {
            viewHolder.titleText.setText(newsTypeList[i]);
        }
        return cpt;
    }

    private static class ViewHolder {
        Text titleText;
    }
}
